<template>
  <el-dialog :title="fileName+ ' - 预览'" :fullscreen="true" :visible.sync="fileDialogVisible" @close="closeDialog">
    <div v-loading="loading" element-loading-text="拼命加载中"
         element-loading-spinner="el-icon-loading"
         element-loading-background="rgba(0, 0, 0, 0.8)">
      <vue-office-docx
          v-if="type=='docx' || type=='doc'"
          :src="fileBlob"
          style="height: 100vh;"
          @rendered="renderedHandler"
          @error="errorHandler"
      />
      <vue-office-pdf
          :staticFileUrl="''"
          v-if="type=='pdf'"
          :src="fileBlob"
          style="height: 100vh;"
          @rendered="renderedHandler"
          @error="errorHandler"
      />
      <vue-office-excel
          v-if="type=='xlsx'"
          :src="fileBlob"
          style="height: 100vh;"
          @rendered="renderedHandler"
          @error="errorHandler"
      />
      <div v-if="type=='xls'">
        <div id="table">
          <el-table :data="excelData" border stripe
                    :header-cell-style="{'background':'#F5F4F7'}">
            <el-table-column
                type="index"
                label="序号"
                width="60"
                :resizable="false"
                align="center"/>
            <el-table-column
                v-for="(value, key, index) in excelData[maxIndex]"
                :key="index"
                :prop="key"
                :label="key"></el-table-column>
          </el-table>
        </div>
      </div>

      <div v-if="type=='img'" style="width: 100%;text-align: center">
        <el-image  style="max-width: 800px; max-height: 1080px"
                   :src="fileBlob"
                   :preview-src-list="[fileBlob]">
        </el-image>
      </div>

      <div v-if="type=='txt'" style="width: 100%;">
        <el-form style="padding: 0 20px">
          <el-form-item label="请选择编码:">
            <el-select clearable  v-model="txtDecode"  size="small" style="width:200px" @change="changeTxtDecode">
              <el-option label="utf-8" value="utf-8"></el-option>
              <el-option label="gbk" value="gbk"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="内容预览:">
            <el-input type="textarea" autosize v-model="fileBlob" readonly></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog" size="small">返 回</el-button>
      </span>
  </el-dialog>
</template>

<script>
//引入VueOfficeDocx组件
import VueOfficeDocx from '@vue-office/docx'
import VueOfficePdf from '@vue-office/pdf'
import VueOfficeExcel from '@vue-office/excel'
//引入相关样式
import '@vue-office/docx/lib/index.css'
import '@vue-office/excel/lib/index.css'

import XLSX from "xlsx";
import {sysFileDownload} from '@/api/sysFile'

export default {
  components: {
    VueOfficeDocx, VueOfficePdf, VueOfficeExcel
  },
  props: {
    fileName: {
      default: ""
    },
    fileId: {
      default: ""
    },
    visible: {
      default: false
    },
  },
  data() {
    return {
      fileDialogVisible: false,
      fileBlob: "",
      loading: true,
      type: true,

      txtDecode:'utf-8',
      excelData: [],
      maxIndex: 0
    }
  },
  watch: {
    visible(val) {
      this.fileDialogVisible = val
      if (val) {
        this.fileBlob = undefined
        this.type = undefined
        let name = this.fileName
        if (name.indexOf(".") === -1) {
          this.showError()
          return
        }
        if (name.endsWith(".")) {
          this.showError()
          return
        }
        let suffix = name.substring(name.lastIndexOf(".") + 1)

        let canPreviewType = ['txt','xls', 'xlsx', 'pdf', 'doc', 'docx','xbm','tif','pjp','svgz','jpg','jpeg','ico','tiff','gif','svg','jfif','webp','png','bmp','pjpeg','avif']
        if (canPreviewType.indexOf(suffix) === -1) {
          this.showError()
          return
        }

        this.type = suffix

        this.loading = true
        if (this.type === 'xls') {
          this.readWorkbookFromRemoteFile()
        } else {
          this.loadFile(suffix)
        }
      }
    },
  },
  methods: {
    changeTxtDecode(){
      this.loadFile('txt')
    },
    loadFile(suffix){
      var that = this
      let imageType = ['xbm','tif','pjp','svgz','jpg','jpeg','ico','tiff','gif','svg','jfif','webp','png','bmp','pjpeg','avif']
      if (imageType.indexOf(suffix) !== -1){
        this.type = "img"
      }
      sysFileDownload("downloadPersonalFile", {"fileId": this.fileId,"noAutoDownload":'1'}).then(response => {
        if (response) {
          const blob = new Blob([response.data])
          if (imageType.indexOf(suffix) !== -1){
            const objectURL = URL.createObjectURL(blob);
            this.fileBlob = objectURL
            this.renderedHandler()
          }else if (suffix === 'txt'){
            const reader = new FileReader();
            reader.readAsText(blob, this.txtDecode);
            reader.onload = function () {
              that.fileBlob =reader.result
              that.renderedHandler()
            }
          }else{
            this.fileBlob = blob
          }
        }
      })
    },
    showError(){
      const that = this
      this.$alert('暂不支持预览该格式文件!', '提示', {
        confirmButtonText: '确定',
        callback: action => {
          that.loading = false
          that.closeDialog()
        }
      });
    },
    readWorkbookFromRemoteFile() {
      let _this = this;
      sysFileDownload("downloadPersonalFile", {
        "fileId": this.fileId,
        "noAutoDownload": '1'
      }, 'arraybuffer').then(response => {
        if (response) {
          const data = new Uint8Array(response.data);
          const workbook = XLSX.read(data, {type: "array"});
          const sheetNames = workbook.SheetNames; // 工作表名称集合
          _this.workbook = workbook;
          _this.getTable(sheetNames[0]);
          // })
          _this.renderedHandler()
        } else {
          _this.errorHandler()
        }
      })
    },
    getTable(sheetName) {
      const worksheet = this.workbook.Sheets[sheetName];
      this.excelData = XLSX.utils.sheet_to_json(worksheet);
      //取数组对象中，对象的key最长的一个进行赋值操作
      let arr = []
      let obj = {}
      arr.push(obj)
      let mapObj = new Map()
      for (let i = 0; i < this.excelData.length; i++) {
        let arrLength = 0
        for (let key in this.excelData[i]) {
          arrLength++
        }
        mapObj.set(i, arrLength)
      }
      let contrastNum = 0
      this.maxIndex = 0
      mapObj.forEach((value, key, self) => {
        if (value > contrastNum) {
          contrastNum = value
          this.maxIndex = key
        }
      });
    },
    closeDialog() {
      this.fileDialogVisible = false
      this.$emit('close')
    },

    renderedHandler() {
      this.loading = false
    },
    errorHandler() {
      if (this.loading) {
        this.loading = false
        this.$message({
          message: "加载失败，请重试！",
          type: 'error'
        })
      }
    }
  }
}
</script>
